@echo off
setlocal enabledelayedexpansion

REM 设置基路径，例如C:\GoldBell\Pic
set "base_path=C:\GoldBell\Pic"

REM 获取当前年份和月份
for /f "tokens=2 delims==" %%i in ('"wmic os get localdatetime /value"') do set datetime=%%i
set "current_year=!datetime:~0,4!"
set "current_month=!datetime:~4,2!"

REM 计算最近7个月的年和月，存入数组
set "count=0"
for /L %%i in (0,1,6) do (
    set /a "month=!current_month!-%%i"
    set /a "year=!current_year!"

    if !month! lss 1 (
        set /a "month+=12"
        set /a "year-=1"
    )

    REM 格式化月份为两位数
    if !month! lss 10 set "month=0!month!"
    
    set "keep_!count!=!year!\!month!"
    set /a count+=1
)

REM 遍历年份文件夹，删除不在最近7个月范围内的月份文件夹
for /D %%Y in ("%base_path%\*") do (
    if exist "%%Y" (
        set "year_folder=%%~nxY"
        
        REM 确保年份文件夹名称是四位数字
        if "!year_folder!" geq "1000" if "!year_folder!" leq "9999" (
            for /D %%M in ("%%Y\*") do (
                set "month_folder=%%~nxM"
                
                REM 确保月份文件夹名称是两位数字
                if "!month_folder!" geq "01" if "!month_folder!" leq "12" (
                    set "keep=0"
                    
                    REM 检查是否在保留范围内
                    for /L %%j in (0,1,6) do (
                        if "!year_folder!\!month_folder!"=="!keep_%%j!" set "keep=1"
                    )
                    
                    REM 如果不在保留范围内则删除
                    if "!keep!"=="0" (
                        echo Deleting folder: %%M
                        rd /s /q "%%M"
                    ) else (
                        echo Keeping folder: %%M
                    )
                )
            )

            REM 检查年份文件夹是否为空，如果为空则删除
            dir "%%Y" /b | findstr . >nul
            if errorlevel 1 (
                echo Deleting empty year folder: %%Y
                rd /s /q "%%Y"
            )
        )
    )
)

endlocal